package com.reggie.background.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.background.common.ThreadLocalUtils;
import com.reggie.background.entity.*;
import com.reggie.background.exception.CustomException;
import com.reggie.background.service.*;
import com.reggie.background.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 1
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2022-07-15 14:14:23
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {
    @Autowired
    private UserService userService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private OrderDetailService orderDetailService;

    @Transactional
    @Override
    public Boolean saveOrder(Orders orders) {

        //查询下单用户得信息
        Long userid = ThreadLocalUtils.getThreadLocalValue();
        User user = userService.getById(userid);

        //生成订单号
        String ordersNum = String.valueOf(IdWorker.getId());

        //查询地址,并插入订单中
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null) {
            throw new CustomException("收货信息不能为空哟！");
        }


        //查询购物车内得信息


        LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
        qw.eq(ShoppingCart::getUserId, userid);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(qw);
        if (shoppingCarts == null || shoppingCarts.size() == 0) {
            throw new CustomException("购物车空空如也，不能结账哟！");
        }

        List<OrderDetail> collect = shoppingCarts.stream().map(item -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(Long.valueOf(ordersNum));
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());

            return orderDetail;
        }).collect(Collectors.toList());
        //总价计算
        BigDecimal account = shoppingCarts.stream().map(item -> {
            BigDecimal multiply = item.getAmount().multiply(new BigDecimal(item.getNumber()));
            return multiply;
        }).reduce(new BigDecimal(0), BigDecimal::add);
        //插入订单表一条订单
        orders.setNumber(ordersNum);
        orders.setOrderTime(new Date());
        orders.setCheckoutTime(new Date());
        orders.setStatus(2);
        orders.setUserId(userid);
        orders.setAmount(account);
        orders.setPhone(addressBook.getPhone());
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        boolean result1 = this.save(orders);
        //插入订单关系表：多条数据
        orderDetailService.saveBatch(collect);
        //清空购物车信息
        LambdaQueryWrapper<ShoppingCart> lqw=new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId,user.getId());
        boolean result2 = shoppingCartService.remove(lqw);
        return result1&&result2;
    }
}




